package com.example.demo.config;

import com.example.demo.interceptor.SecInterceptor;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.ErrorPageRegistrar;
import org.springframework.boot.web.server.ErrorPageRegistry;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;

import java.sql.SQLException;
import java.util.Locale;

@Configuration
public class SelfWebMcvConfigurer implements WebMvcConfigurer, ErrorPageRegistrar {
    //拦截器
    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {
        LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
        localeChangeInterceptor.setParamName("lang");
        return localeChangeInterceptor;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        WebMvcConfigurer.super.addInterceptors(registry);
        registry.addInterceptor(localeChangeInterceptor());

        registry.addInterceptor(new SecInterceptor()).addPathPatterns("/sec/**");
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        WebMvcConfigurer.super.addViewControllers(registry);
        registry.addViewController("/sec/private").setViewName("/private");
        registry.addViewController("/error/sql_ex").setViewName("/error/sql_ex");
    }

    //语言和地区的解析器
//    //session方式实现语言地区的切换
//    @Bean
//    public SessionLocaleResolver localeResolver() {
//        SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver();
//        sessionLocaleResolver.setDefaultLocale(Locale.CHINESE);
//        return sessionLocaleResolver;
//    }

    //cookie实现语言地区
    @Bean
    public CookieLocaleResolver localeResolver() {
        CookieLocaleResolver resolver = new CookieLocaleResolver();
        resolver.setDefaultLocale(Locale.CHINESE);
        return resolver;
    }
    //利用ErrorPageRegistrar进行全局异常处理
    @Override
    public void registerErrorPages(ErrorPageRegistry registry) {
        registry.addErrorPages(new ErrorPage(SQLException.class,"/error/sql_ex"));
    }
}
